package x.ovo.wechat.bot;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import x.ovo.wechat.bot.common.entity.event.MessageEvent;
import x.ovo.wechat.bot.common.entity.message.TextMessage;
import x.ovo.wechat.bot.common.event.Event;
import x.ovo.wechat.bot.common.event.EventListener;
import x.ovo.wechat.bot.common.util.WechatUtil;

@Slf4j(topic = "工具集合")
public class ToolsListener extends EventListener<MessageEvent<TextMessage>> {

    private static final String OIL_URL = "https://api.qqsuu.cn/api/dm-oilprice?prov=";
    private static final String SKILL_URL = "https://api.qqsuu.cn/api/dm-qiaomen";

    @Override
    public boolean support(Event<?> event) {
        return event instanceof MessageEvent && event.getSource() instanceof TextMessage && (!((TextMessage) event.getSource()).isGroup() || ((TextMessage) event.getSource()).isAtMe());
    }

    @Override
    public void onEvent(MessageEvent<TextMessage> event) {
        String content = WechatUtil.format(event.getContent().replaceAll("@", "").replaceAll(this.context.getLoginSession().getNickName(), "")).trim();
        String form = event.getSource().getFromUser().getUserName();

        if (content.contains("油价")) {
            try {
                String prov = content.replace("油价", "");
                JSONObject object = JSONUtil.parseObj(HttpUtil.get(OIL_URL + prov)).getJSONObject("data");
                String s = StrUtil.format("油价小助手 - [{}]油价\n---------------\n0 号: {}\n89 号: {}\n92 号: {}\n95 号: {}\n98 号: {}\n---------------\n{}",
                        object.getStr("prov"),
                        object.getStr("p0"),
                        object.getStr("p89"),
                        object.getStr("p92"),
                        object.getStr("p95"),
                        object.getStr("p98"),
                        object.getStr("time")
                );
                this.context.getApi().sendText(form, s);
            } catch (Exception e) {
                log.error("获取实时油价失败", e);
            }
            return;
        }
        if (content.contains("生活小技巧")) {
            try {
                String s = JSONUtil.parseObj(HttpUtil.get(SKILL_URL)).getJSONObject("data").getStr("content");
                this.context.getApi().sendText(form, s);
            } catch (Exception e) {
                log.error("获取生活小技巧失败", e);
            }
            return;
        }
    }
}
